#!/usr/bin/env python3
import asyncio

from aiogram import Bot, Dispatcher
from aiogram.client.bot import DefaultBotProperties

from factories import bot_commands, generate_screens
from handlers import router
from middlewares import (AntiFloodMiddleware, IsBotMiddleware,
                             IsGroupMessageMiddleware)
from settings import settings
from utils import alert_admin, debugger, log, set_commands


# initialize bot
async def on_bot_init(bot: Bot):
    generate_screens()
    await set_commands(bot, commands=bot_commands)
    await alert_admin(bot, f"Бот поднялся")


# shutdown bot
async def on_bot_down(bot: Bot):
    await alert_admin(bot, f"Бот упал")


# main function
async def main():

    #create new bot instance
    bot = Bot(token=settings.bots.tg_token, default=DefaultBotProperties(parse_mode='HTML'))

    # create dispatcher
    dp = Dispatcher()

    # register middlewares
    dp.message.middleware(IsBotMiddleware(bot))
    dp.message.middleware(IsGroupMessageMiddleware())
    dp.message.middleware(AntiFloodMiddleware())

    # register all routers
    dp.include_routers(router)

    #
    dp.startup.register(on_bot_init)
    dp.shutdown.register(on_bot_down)

    try:
        debugger.debug("Bot ready")
        await bot.delete_webhook(drop_pending_updates=True)
        await dp.start_polling(bot)
    finally:
        log.warning("Bot stoped")
        await dp.session.close()


if __name__ == "__main__":
    asyncio.run(main())
